// ==UserScript==
// @name         青龙COOKIE更新
// @namespace    https://gtjs-9gjbu0mx.maozi.io/2025/10/10/you-hou-qing-long/
// @match        https://*/*
// @grant        GM_xmlhttpRequest
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_registerMenuCommand
// @grant        GM_cookie
// @grant        unsafeWindow
// @connect      *
// @version      1.5.0
// @updateURL    https://gtjs-9gjbu0mx.maozi.io/user-scripts/qinglong.user.js
// @require      https://fastly.jsdelivr.net/gh/WhiteSevs/TamperMonkeyScript@86be74b83fca4fa47521cded28377b35e1d7d2ac/lib/CoverUMD/index.js 
// @require      https://fastly.jsdelivr.net/npm/@whitesev/utils@2.9.0/dist/index.umd.js 
// @require      https://fastly.jsdelivr.net/npm/@whitesev/domutils@1.7.0/dist/index.umd.js 
// @require      https://fastly.jsdelivr.net/npm/qmsg@1.5.0/dist/index.umd.js 
// @require      https://fastly.jsdelivr.net/gh/WhiteSevs/TamperMonkeyScript@886625af68455365e426018ecb55419dd4ea6f30/lib/CryptoJS/index.js 
// ==/UserScript==

(function () {
    'use strict';

    // -------------------------- 整合新脚本核心工具类 --------------------------
    const _GM = typeof GM !== "undefined" ? GM : void 0;
    const _GM_cookie = typeof GM_cookie !== "undefined" ? GM_cookie : void 0;
    const _GM_getValue = typeof GM_getValue !== "undefined" ? GM_getValue : void 0;
    const _GM_setValue = typeof GM_setValue !== "undefined" ? GM_setValue : void 0;
    const _unsafeWindow = typeof unsafeWindow !== "undefined" ? unsafeWindow : window;

    class StorageUtils {
        constructor(storageKey) {
            this.storageKey = storageKey;
        }

        getValue(key, defaultValue) {
            const data = _GM_getValue(this.storageKey) || {};
            return data[key] ?? defaultValue;
        }

        setValue(key, value) {
            const data = _GM_getValue(this.storageKey) || {};
            data[key] = value;
            _GM_setValue(this.storageKey, data);
        }
    }

    class CookieTool {
        constructor() {
            this.cookieMethods = [
                { id: 'gm', name: 'GM API获取' },
                { id: 'document', name: 'document.cookie获取' },
                { id: 'cookieStore', name: 'cookieStore API获取' },
                { id: 'hybrid', name: '混合模式（GM优先，失败则用document）' }
            ];
            this.cookieStorage = new StorageUtils('cookie_tool_settings');
            this.selectedMethod = this.cookieStorage.getValue('cookieMethod', 'gm');
        }

        saveUserPreferences() {
            this.cookieStorage.setValue('cookieMethod', this.selectedMethod);
        }

        async getCookies() {
            try {
                switch (this.selectedMethod) {
                    case 'gm':
                        return await this.getCookiesByGM();
                    case 'document':
                        return this.getCookiesByDocument();
                    case 'cookieStore':
                        return await this.getCookiesByCookieStore();
                    case 'hybrid':
                        const gmCookies = await this.getCookiesByGM().catch(() => null);
                        return gmCookies || this.getCookiesByDocument();
                    default:
                        return this.getCookiesByGM();
                }
            } catch (e) {
                Qmsg.error(`获取Cookie失败: ${e.message}`);
                return '';
            }
        }

        async getCookiesByGM() {
            if (!_GM_cookie?.list) {
                Qmsg.warning('GM_cookie API不可用，切换为document方式');
                return this.getCookiesByDocument();
            }
            return new Promise((resolve) => {
                _GM_cookie.list({ url: window.location.href }, (cookies) => {
                    if (!cookies || !cookies.length) {
                        resolve('');
                        return;
                    }
                    const cookieStr = cookies.map(c => `${c.name}=${c.value}`).join('; ');
                    resolve(cookieStr);
                });
            });
        }

        getCookiesByDocument() {
            return document.cookie ? document.cookie.split('; ').join('; ') : '';
        }

        async getCookiesByCookieStore() {
            if (!window.cookieStore) {
                Qmsg.error('当前浏览器不支持cookieStore API，切换为document方式');
                return this.getCookiesByDocument();
            }
            try {
                const cookies = await window.cookieStore.getAll();
                return cookies?.length ? cookies.map(c => `${c.name}=${c.value}`).join('; ') : '';
            } catch (e) {
                Qmsg.error(`cookieStore获取失败: ${e.message}，切换为document方式`);
                return this.getCookiesByDocument();
            }
        }

        getUserAgent() {
            return navigator.userAgent || '';
        }
    }

    // -------------------------- 初始化Cookie工具（全局实例） --------------------------
    let cookieTool;
    // 等待DOM加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            cookieTool = new CookieTool();
        });
    } else {
        cookieTool = new CookieTool();
    }

    // -------------------------- 原脚本逻辑 --------------------------
    function loadTailwindCSS() {
        if (document.getElementById('tailwindcss-cdn-ql')) return;
        const tailwindScript = document.createElement('script');
        tailwindScript.id = 'tailwindcss-cdn-ql';
        tailwindScript.src = 'https://cdn.tailwindcss.com';
        tailwindScript.onload = () => {
            const configScript = document.createElement('script');
            configScript.textContent = `
                tailwind.config = {
                    theme: {
                        extend: {
                            colors: { primary: '#2563eb', secondary: '#f59e0b' },
                            animation: { 'fade-in': 'fadeIn 0.3s ease-in-out', 'slide-in': 'slideIn 0.3s ease-out' },
                            keyframes: {
                                fadeIn: { '0%': { opacity: '0' }, '100%': { opacity: '1' } },
                                slideIn: { '0%': { opacity: '0', transform: 'translate(-50%, -55%)' }, '100%': { opacity: '1', transform: 'translate(-50%, -50%)' } }
                            }
                        }
                    }
                }
            `;
            document.head.appendChild(configScript);
        };
        document.head.appendChild(tailwindScript);
    }
    loadTailwindCSS();

    const presetEnvs = [
        { envName: 'TYYP_COOKIE', remark: '天翼云盘', urlPatterns: ['cloud.189.cn'], updateMode: 'ua_and_cookie' },
        { envName: 'BIAOZHUN_COOKIE', remark: '标准网积分', urlPatterns: ['www.biaozhun.org'], updateMode: 'cookie_only' },
        { envName: 'BZCOM_COOKIE', remark: '标准网铜钱', urlPatterns: ['bbs.biaozhuns.com'], updateMode: 'cookie_only' },
        { envName: 'FN_COOKIE', remark: '飞牛', urlPatterns: ['club.fnnas.com'], updateMode: 'cookie_only' },
        { envName: 'QUARK_COOKIE', remark: '夸克', urlPatterns: ['quark'], updateMode: 'cookie_only' }
    ];

    const defaultParams = { QL_URL: '', CLIENT_ID: '', CLIENT_SEC: '', ENV_NAME: '_COOKIE', REMARKS: '' };
    const QL_URL = GM_getValue('QL_URL', defaultParams.QL_URL);
    const CLIENT_ID = GM_getValue('CLIENT_ID', defaultParams.CLIENT_ID);
    const CLIENT_SEC = GM_getValue('CLIENT_SEC', defaultParams.CLIENT_SEC);
    const ENV_NAME = GM_getValue('ENV_NAME', defaultParams.ENV_NAME);
    const REMARKS = GM_getValue('REMARKS', defaultParams.REMARKS);

    function validateAndFormatUrl(url) {
        if (!url) throw new Error('青龙面板地址不能为空，请先在设置中填写');
        if (!url.startsWith('http://') && !url.startsWith('https://')) url = 'http://' + url;
        if (url.endsWith('/')) url = url.slice(0, -1);
        try { new URL(url); return url; } 
        catch (e) { throw new Error(`无效的URL格式: ${url}，请检查地址是否正确`); }
    }

    function getMatchedEnv() {
        const currentUrl = window.location.href.toLowerCase();
        for (const env of presetEnvs) {
            for (const pattern of env.urlPatterns) {
                if (currentUrl.includes(pattern.toLowerCase())) return env;
            }
        }
        return null;
    }

    // -------------------------- 核心修改：整合所有功能到一个对话框 --------------------------
    async function showMainDialog() {
        // 确保Cookie工具已初始化
        if (!cookieTool) {
            Qmsg.warning('Cookie工具初始化中，请稍后再试');
            return;
        }

        const dialogContainer = document.createElement('div');

        // 遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'fixed inset-0 bg-black/50 backdrop-blur-sm z-[1000000] animate-fade-in';
        dialogContainer.appendChild(overlay);

        // 对话框主体
        const dialog = document.createElement('div');
        dialog.className = 'fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-white rounded-xl shadow-xl max-w-[90%] w-full max-w-[600px] max-h-[80vh] overflow-y-auto animate-slide-in z-[1000001]';
        dialogContainer.appendChild(dialog);

        // 对话框标题
        const title = document.createElement('h2');
        title.textContent = '青龙Cookie更新与设置';
        title.className = 'text-2xl font-semibold text-gray-800 text-center py-4 border-b border-gray-100';
        dialog.appendChild(title);

        // Tab容器 - 增加了“Cookie工具”Tab
        const tabContainer = document.createElement('div');
        tabContainer.className = 'flex border-b border-gray-200';
        dialog.appendChild(tabContainer);

        // 创建三个Tab按钮
        const updateTab = document.createElement('button');
        updateTab.textContent = '更新CK';
        updateTab.className = 'flex-1 py-3 text-center font-medium transition-all duration-200';
        tabContainer.appendChild(updateTab);

        const settingsTab = document.createElement('button');
        settingsTab.textContent = '青龙设置';
        settingsTab.className = 'flex-1 py-3 text-center font-medium transition-all duration-200';
        tabContainer.appendChild(settingsTab);

        const cookieToolTab = document.createElement('button');
        cookieToolTab.textContent = 'Cookie工具';
        cookieToolTab.className = 'flex-1 py-3 text-center font-medium transition-all duration-200';
        tabContainer.appendChild(cookieToolTab);

        // 内容容器
        const form = document.createElement('form');
        form.className = 'p-4 space-y-5';
        dialog.appendChild(form);

        // 创建三个内容面板
        const updatePanel = document.createElement('div');
        updatePanel.className = 'w-full';
        const settingsPanel = document.createElement('div');
        settingsPanel.className = 'w-full hidden';
        const cookieToolPanel = document.createElement('div');
        cookieToolPanel.className = 'w-full hidden';
        form.appendChild(updatePanel);
        form.appendChild(settingsPanel);
        form.appendChild(cookieToolPanel);

        // 工具函数：创建输入行、输入框、文本域
        const createInputRow = (labelText, inputElement) => {
            const row = document.createElement('div');
            row.className = 'flex flex-col gap-2 w-full';
            const label = document.createElement('label');
            label.textContent = labelText;
            label.className = 'text-sm font-medium text-gray-600';
            const inputContainer = document.createElement('div');
            inputContainer.className = 'w-full';
            inputContainer.appendChild(inputElement);
            row.appendChild(label);
            row.appendChild(inputContainer);
            return row;
        };
        const createInput = (value, placeholder, type = 'text') => {
            const input = document.createElement('input');
            input.type = type;
            input.value = value;
            input.placeholder = placeholder;
            input.className = 'w-full px-4 py-3 border border-gray-200 rounded-lg text-base transition-all duration-200 focus:border-gray-400 focus:outline-none focus:ring-1 focus:ring-primary/20';
            return input;
        };
        const createTextarea = (value, placeholder) => {
            const textarea = document.createElement('textarea');
            textarea.value = value;
            textarea.placeholder = placeholder;
            textarea.className = 'w-full px-4 py-3 border border-gray-200 rounded-lg text-base transition-all duration-200 h-28 resize-y font-mono focus:border-gray-400 focus:outline-none focus:ring-1 focus:ring-primary/20';
            return textarea;
        };

        // 1. 青龙设置面板 (原设置面板内容)
        const qlUrlInput = createInput(QL_URL, '必填！例：http://192.168.1.100:5700 或 https://ql.example.com');
        const qlUrlRow = createInputRow('青龙面板地址：', qlUrlInput);
        settingsPanel.appendChild(qlUrlRow);
        const clientIdInput = createInput(CLIENT_ID, '必填！青龙面板→系统设置→应用设置中获取');
        const clientIdRow = createInputRow('Client ID：', clientIdInput);
        settingsPanel.appendChild(clientIdRow);
        const clientSecInput = createInput(CLIENT_SEC, '必填！与Client ID一同获取');
        const clientSecRow = createInputRow('Client Secret：', clientSecInput);
        settingsPanel.appendChild(clientSecRow);

        // 2. 更新CK面板 (原更新面板内容)
        const presetSelect = document.createElement('select');
        presetSelect.className = 'w-full px-4 py-3 border border-gray-200 rounded-lg text-base text-gray-800 bg-white transition-all duration-200 appearance-none bg-[url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'16\' height=\'16\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%2364748b\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\'%3E%3Cpolyline points=\'6 9 12 15 18 9\'%3E%3C/polyline%3E%3C/svg%3E")] bg-no-repeat bg-right-[15px] bg-center focus:border-gray-400 focus:outline-none focus:ring-1 focus:ring-primary/20';
        const defaultOption = document.createElement('option');
        defaultOption.value = '';
        defaultOption.textContent = '请选择或手动输入...';
        presetSelect.appendChild(defaultOption);
        presetEnvs.forEach(env => {
            const option = document.createElement('option');
            option.value = env.envName;
            option.textContent = `${env.envName} (${env.remark})`;
            presetSelect.appendChild(option);
        });
        const presetRow = createInputRow('预设环境变量：', presetSelect);
        updatePanel.appendChild(presetRow);

        const envNameInput = createInput(ENV_NAME, '例：TYYP_COOKIE（与青龙面板中一致）');
        const envNameRow = createInputRow('环境变量名称：', envNameInput);
        updatePanel.appendChild(envNameRow);
        const remarksInput = createInput(REMARKS, '例：天翼云盘Cookie（便于识别）');
        const remarksRow = createInputRow('备注信息：', remarksInput);
        updatePanel.appendChild(remarksRow);

        const updateModeSelect = document.createElement('select');
        updateModeSelect.className = 'w-full px-4 py-3 border border-gray-200 rounded-lg text-base text-gray-800 bg-white transition-all duration-200 appearance-none bg-[url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'16\' height=\'16\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%2364748b\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\'%3E%3Cpolyline points=\'6 9 12 15 18 9\'%3E%3C/polyline%3E%3C/svg%3E")] bg-no-repeat bg-right-[15px] bg-center focus:border-gray-400 focus:outline-none focus:ring-1 focus:ring-primary/20';
        const optionCookieOnly = document.createElement('option');
        optionCookieOnly.value = 'cookie_only';
        optionCookieOnly.textContent = '只更新Cookie';
        const optionUAandCookie = document.createElement('option');
        optionUAandCookie.value = 'ua_and_cookie';
        optionUAandCookie.textContent = '同时更新UA和Cookie';
        updateModeSelect.appendChild(optionCookieOnly);
        updateModeSelect.appendChild(optionUAandCookie);
        const updateModeRow = createInputRow('更新方式：', updateModeSelect);
        updatePanel.appendChild(updateModeRow);

        const cookieTextarea = createTextarea('', '正在获取Cookie...');
        const cookieRow = createInputRow('Cookie内容：', cookieTextarea);
        updatePanel.appendChild(cookieRow);

        // 异步获取Cookie和UA
        const currentCookie = await cookieTool.getCookies();
        const currentUA = cookieTool.getUserAgent();
        cookieTextarea.value = currentCookie || '未获取到Cookie，请检查获取方式设置';
        cookieTextarea.placeholder = '当前页面Cookie已自动填充，可直接编辑或替换';

        // 预设选择联动
        presetSelect.addEventListener('change', () => {
            const selectedEnv = presetEnvs.find(env => env.envName === presetSelect.value);
            if (selectedEnv) {
                envNameInput.value = selectedEnv.envName;
                remarksInput.value = selectedEnv.remark;
                updateModeSelect.value = selectedEnv.updateMode || 'cookie_only';
            }
        });

        const matchedEnv = getMatchedEnv();
        if (matchedEnv) {
            for (let i = 0; i < presetSelect.options.length; i++) {
                if (presetSelect.options[i].value === matchedEnv.envName) {
                    presetSelect.selectedIndex = i;
                    break;
                }
            }
            envNameInput.value = matchedEnv.envName;
            remarksInput.value = matchedEnv.remark;
            updateModeSelect.value = matchedEnv.updateMode || 'cookie_only';
        }

        // 3. Cookie工具面板 (从CookieTool类中迁移过来)
        const cookieToolTitle = document.createElement('h3');
        cookieToolTitle.textContent = 'Cookie获取方式设置';
        cookieToolTitle.style.margin = '0 0 15px 0';
        cookieToolPanel.appendChild(cookieToolTitle);

        const radioGroup = document.createElement('div');
        radioGroup.style.marginBottom = '20px';
        cookieTool.cookieMethods.forEach(method => {
            const label = document.createElement('label');
            label.style.cssText = 'display: block; margin-bottom: 10px; cursor: pointer;';
            
            const radio = document.createElement('input');
            radio.type = 'radio';
            radio.name = 'cookieMethod';
            radio.value = method.id;
            radio.checked = cookieTool.selectedMethod === method.id;
            radio.addEventListener('change', () => {
                cookieTool.selectedMethod = method.id;
            });

            label.appendChild(radio);
            label.appendChild(document.createTextNode(method.name));
            radioGroup.appendChild(label);
        });
        cookieToolPanel.appendChild(radioGroup);

        const saveCookieToolBtn = document.createElement('button');
        saveCookieToolBtn.type = 'button'; // 重要：不是submit
        saveCookieToolBtn.textContent = '保存Cookie获取方式';
        saveCookieToolBtn.className = 'py-3 px-4 bg-primary text-white border-none rounded-lg cursor-pointer text-base font-medium transition-all duration-200 text-center shadow-md shadow-primary/30 hover:bg-primary/90';
        saveCookieToolBtn.addEventListener('click', () => {
            cookieTool.saveUserPreferences();
            Qmsg.success('Cookie获取方式已保存');
        });
        cookieToolPanel.appendChild(saveCookieToolBtn);

        // Tab切换逻辑
        const showUpdatePanel = () => {
            updatePanel.classList.remove('hidden');
            settingsPanel.classList.add('hidden');
            cookieToolPanel.classList.add('hidden');
            updateTab.classList.add('text-primary', 'border-b-2', 'border-primary');
            updateTab.classList.remove('text-gray-500');
            settingsTab.classList.remove('text-primary', 'border-b-2', 'border-primary');
            settingsTab.classList.add('text-gray-500');
            cookieToolTab.classList.remove('text-primary', 'border-b-2', 'border-primary');
            cookieToolTab.classList.add('text-gray-500');
        };
        const showSettingsPanel = () => {
            updatePanel.classList.add('hidden');
            settingsPanel.classList.remove('hidden');
            cookieToolPanel.classList.add('hidden');
            settingsTab.classList.add('text-primary', 'border-b-2', 'border-primary');
            settingsTab.classList.remove('text-gray-500');
            updateTab.classList.remove('text-primary', 'border-b-2', 'border-primary');
            updateTab.classList.add('text-gray-500');
            cookieToolTab.classList.remove('text-primary', 'border-b-2', 'border-primary');
            cookieToolTab.classList.add('text-gray-500');
        };
        const showCookieToolPanel = () => {
            updatePanel.classList.add('hidden');
            settingsPanel.classList.add('hidden');
            cookieToolPanel.classList.remove('hidden');
            cookieToolTab.classList.add('text-primary', 'border-b-2', 'border-primary');
            cookieToolTab.classList.remove('text-gray-500');
            updateTab.classList.remove('text-primary', 'border-b-2', 'border-primary');
            updateTab.classList.add('text-gray-500');
            settingsTab.classList.remove('text-primary', 'border-b-2', 'border-primary');
            settingsTab.classList.add('text-gray-500');
        };

        // 默认显示哪个面板
        if (QL_URL && CLIENT_ID && CLIENT_SEC) {
            showUpdatePanel();
        } else {
            showSettingsPanel();
        }

        updateTab.addEventListener('click', showUpdatePanel);
        settingsTab.addEventListener('click', showSettingsPanel);
        cookieToolTab.addEventListener('click', showCookieToolPanel);

        // 底部按钮行 - 仅在“更新CK”和“青龙设置”面板显示
        const buttonRow = document.createElement('div');
        buttonRow.className = 'flex gap-3 mt-2 w-full';
        form.appendChild(buttonRow); // 按钮行始终存在，但在不相关面板会被隐藏

        const cancelButton = document.createElement('button');
        cancelButton.type = 'button';
        cancelButton.textContent = '关闭';
        cancelButton.className = 'flex-1 py-3 px-4 bg-gray-100 text-gray-600 border-none rounded-lg cursor-pointer text-base font-medium transition-all duration-200 text-center';
        cancelButton.addEventListener('click', () => dialogContainer.remove());
        buttonRow.appendChild(cancelButton);

        const submitButton = document.createElement('button');
        submitButton.type = 'submit';
        submitButton.textContent = '保存并更新';
        submitButton.className = 'flex-1 py-3 px-4 bg-primary text-white border-none rounded-lg cursor-pointer text-base font-medium transition-all duration-200 text-center shadow-md shadow-primary/30 hover:bg-primary/90';
        buttonRow.appendChild(submitButton);

        dialog.appendChild(form);
        document.body.appendChild(dialogContainer);

        overlay.addEventListener('click', () => dialogContainer.remove());
        dialog.addEventListener('click', (e) => e.stopPropagation());

        // 监听Tab切换，控制提交按钮的显示
        updateTab.addEventListener('click', () => { submitButton.textContent = '保存并更新'; buttonRow.classList.remove('hidden'); });
        settingsTab.addEventListener('click', () => { submitButton.textContent = '保存青龙设置'; buttonRow.classList.remove('hidden'); });
        cookieToolTab.addEventListener('click', () => { buttonRow.classList.add('hidden'); }); // Cookie工具面板不显示提交按钮

        form.onsubmit = async (e) => {
            e.preventDefault();
            try {
                // 验证并保存青龙设置（无论哪个面板提交，都保存设置）
                validateAndFormatUrl(qlUrlInput.value);
                if (!clientIdInput.value.trim()) throw new Error('Client ID不能为空，请从青龙面板获取');
                if (!clientSecInput.value.trim()) throw new Error('Client Secret不能为空，请从青龙面板获取');
                
                GM_setValue('QL_URL', qlUrlInput.value);
                GM_setValue('CLIENT_ID', clientIdInput.value);
                GM_setValue('CLIENT_SEC', clientSecInput.value);
                
                // 如果是在“更新CK”面板提交，则执行更新逻辑
                if (!updatePanel.classList.contains('hidden')) {
                    const ck = cookieTextarea.value.trim();
                    if (!ck) {
                        Qmsg.warning('Cookie内容不能为空！');
                        return;
                    }
                    const remarksValue = remarksInput.value.trim() || '自动更新';
                    GM_setValue('ENV_NAME', envNameInput.value);
                    GM_setValue('REMARKS', remarksValue);

                    const newQL_URL = qlUrlInput.value;
                    const newCLIENT_ID = clientIdInput.value;
                    const newCLIENT_SEC = clientSecInput.value;
                    const newENV_NAME = envNameInput.value;
                    const newREMARKS = remarksValue;
                    
                    const updateMode = updateModeSelect.value;
                    let envValue = ck; // 默认只传cookie
                    if (updateMode === 'ua_and_cookie') {
                        envValue = `ua="${currentUA}";cookie="${ck}";`;
                    }

                    const token = await getToken(newQL_URL, newCLIENT_ID, newCLIENT_SEC);
                    await updateEnv(token, newQL_URL, newENV_NAME, newREMARKS, envValue);
                    Qmsg.success(`${newENV_NAME} 已成功更新到青龙面板！`);
                } else {
                    // 如果是在“青龙设置”面板提交，仅提示保存成功
                    Qmsg.success('青龙面板设置已保存！');
                }
                
                dialogContainer.remove();
            } catch (err) {
                Qmsg.error(`操作失败: ${err.message}`);
            }
        };
    }

    // -------------------------- 核心修改：注册唯一的油猴菜单 --------------------------
    GM_registerMenuCommand('更新青龙CK和设置', showMainDialog);


    function getToken(QL_URL, CLIENT_ID, CLIENT_SEC) {
        return new Promise((resolve, reject) => {
            try {
                const formattedUrl = validateAndFormatUrl(QL_URL);
                const url = `${formattedUrl}/open/auth/token?client_id=${encodeURIComponent(CLIENT_ID)}&client_secret=${encodeURIComponent(CLIENT_SEC)}`;
                GM_xmlhttpRequest({
                    method: 'GET',
                    url: url,
                    responseType: 'json',
                    onload: r => {
                        if (r.status < 200 || r.status >= 300) {
                            return reject(`获取Token失败，HTTP错误: ${r.status}`);
                        }
                        const tk = r.response?.data?.token;
                        tk ? resolve(tk) : reject('获取Token失败，检查Client ID/Secret是否正确');
                    },
                    onerror: () => reject('获取Token网络错误，检查青龙面板地址是否可达')
                });
            } catch (error) {
                reject(error.message);
            }
        });
    }

    function updateEnv(token, QL_URL, ENV_NAME, REMARKS, ck) {
        if (!ck) return Promise.reject('环境变量值为空');
        return new Promise((resolve, reject) => {
            try {
                const formattedUrl = validateAndFormatUrl(QL_URL);
                GM_xmlhttpRequest({
                    method: 'GET',
                    url: `${formattedUrl}/open/envs?searchValue=${encodeURIComponent(ENV_NAME)}`,
                    headers: { Authorization: `Bearer ${token}` },
                    responseType: 'json',
                    onload: r => {
                        if (r.status < 200 || r.status >= 300) {
                            return reject(`查询环境变量失败，HTTP错误: ${r.status}`);
                        }
                        const env = (r.response?.data || []).find(v => v.name === ENV_NAME);
                        const body = { name: ENV_NAME, value: ck, remarks: REMARKS };
                        const url = `${formattedUrl}/open/envs`;
                        const method = env ? 'PUT' : 'POST';
                        if (env) body.id = env.id;
                        GM_xmlhttpRequest({
                            method,
                            url,
                            headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
                            data: JSON.stringify(body),
                            responseType: 'json',
                            onload: (response) => {
                                if (response.status < 200 || response.status >= 300) {
                                    return reject(`更新环境变量失败，HTTP错误: ${response.status}`);
                                }
                                resolve();
                            },
                            onerror: () => reject('更新环境变量网络错误，检查青龙面板地址是否可达')
                        });
                    },
                    onerror: () => reject('查询环境变量网络错误，检查青龙面板地址是否可达')
                });
            } catch (error) {
                reject(error.message);
            }
        });
    }

    // 初始化函数现在只负责加载Tailwind和CookieTool，不再创建按钮
    function init() {
        // Tailwind 和 CookieTool 已经在脚本加载时处理
        // 此处为空，因为所有交互都移到了油猴菜单
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();